<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MySQL可视化学习平台</title>
    <!-- 使用本地Tailwind CSS避免生产环境警告 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .sql-editor {
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 14px;
            line-height: 1.5;
        }
        .table-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1rem;
        }
        .sidebar {
            transition: all 0.3s ease;
        }
        .chart-container {
            background: white;
            border-radius: 0.5rem;
            padding: 1rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .min-h-200 {
            min-height: 200px;
        }
        .max-h-90vh {
            max-height: 90vh;
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-blue-600 text-white shadow-lg">
        <div class="container mx-auto px-4">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-3">
                    <i class="fas fa-database text-2xl"></i>
                    <h1 class="text-2xl font-bold">MySQL可视化学习平台</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <button onclick="toggleTheme()" class="p-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-palette"></i>
                    </button>
                    <button onclick="exportData()" class="p-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container mx-auto px-4 py-6">
        <div class="flex gap-6">
            <!-- 左侧边栏 -->
            <div class="sidebar w-80 flex-shrink-0">
                <!-- 数据库状态卡片 -->
                <div class="bg-white rounded-lg shadow-md p-4 mb-6">
                    <h2 class="text-lg font-semibold mb-3 flex items-center">
                        <i class="fas fa-chart-bar mr-2"></i>数据库状态
                    </h2>
                    <div id="dbStats" class="space-y-3">
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600">表数量:</span>
                            <span id="tableCount" class="font-semibold">-</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600">总数据量:</span>
                            <span id="totalRows" class="font-semibold">-</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600">连接状态:</span>
                            <span class="text-green-500 font-semibold">正常</span>
                        </div>
                    </div>
                </div>

                <!-- 表列表 -->
                <div class="bg-white rounded-lg shadow-md p-4">
                    <div class="flex justify-between items-center mb-3">
                        <h2 class="text-lg font-semibold flex items-center">
                            <i class="fas fa-table mr-2"></i>数据表
                        </h2>
                        <div class="flex space-x-2">
                            <button onclick="refreshTables()" class="text-blue-500 hover:text-blue-700 p-1">
                                <i class="fas fa-sync-alt"></i>
                            </button>
                            <button onclick="createNewTable()" class="text-green-500 hover:text-green-700 p-1">
                                <i class="fas fa-plus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <input type="text" id="tableSearch" placeholder="搜索表..."
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <div id="tableList" class="space-y-2 max-h-96 overflow-y-auto">
                        <div class="animate-pulse text-center py-4">加载表列表中...</div>
                    </div>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="flex-1">
                <!-- SQL编辑器卡片 -->
                <div class="bg-white rounded-lg shadow-md mb-6">
                    <div class="border-b px-6 py-4 flex justify-between items-center">
                        <h2 class="text-xl font-semibold flex items-center">
                            <i class="fas fa-code mr-3"></i>SQL 编辑器
                        </h2>
                        <div class="flex space-x-2">
                            <button onclick="formatSQL()" class="px-4 py-2 bg-gray-500 text-white rounded-lg text-sm hover:bg-gray-600">
                                <i class="fas fa-indent mr-2"></i>格式化
                            </button>
                            <button onclick="saveSQL()" class="px-4 py-2 bg-purple-500 text-white rounded-lg text-sm hover:bg-purple-600">
                                <i class="fas fa-save mr-2"></i>保存
                            </button>
                        </div>
                    </div>
                    <div class="p-6">
                        <div class="mb-4">
                            <textarea
                                id="sqlEditor"
                                class="sql-editor w-full h-48 border border-gray-300 rounded-lg p-4 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                                placeholder="输入您的SQL语句...&#10;示例: SELECT * FROM users;"
                                spellcheck="false"
                            ></textarea>
                        </div>
                        <div class="flex justify-between items-center">
                            <div class="flex space-x-3">
                                <button onclick="executeSQL()" class="bg-blue-500 hover:bg-blue-600 text-white px-8 py-3 rounded-lg font-semibold flex items-center">
                                    <i class="fas fa-play-circle mr-2"></i>执行 SQL
                                </button>
                                <button onclick="clearEditor()" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-3 rounded-lg font-medium flex items-center">
                                    <i class="fas fa-eraser mr-2"></i>清空
                                </button>
                            </div>
                            <div class="flex space-x-2">
                                <button onclick="showExamples()" class="px-4 py-2 border border-blue-500 text-blue-500 rounded-lg text-sm hover:bg-blue-50 flex items-center">
                                    <i class="fas fa-graduation-cap mr-2"></i>学习示例
                                </button>
                                <button onclick="showHistory()" class="px-4 py-2 border border-green-500 text-green-500 rounded-lg text-sm hover:bg-green-50 flex items-center">
                                    <i class="fas fa-history mr-2"></i>历史记录
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 结果展示区 -->
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-6 mb-6">
                    <!-- 执行结果 -->
                    <div class="bg-white rounded-lg shadow-md">
                        <div class="border-b px-6 py-4">
                            <h2 class="text-xl font-semibold flex items-center">
                                <i class="fas fa-list-alt mr-3"></i>执行结果
                            </h2>
                        </div>
                        <div class="p-6">
                            <div id="sqlResult" class="min-h-200">
                                <div class="text-gray-400 text-center py-12">
                                    <i class="fas fa-database text-4xl mb-3"></i>
                                    <p class="text-lg">执行结果将显示在这里</p>
                                    <p class="text-sm mt-2">尝试执行一些SQL语句来查看结果</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 数据可视化 -->
                    <div class="bg-white rounded-lg shadow-md">
                        <div class="border-b px-6 py-4">
                            <h2 class="text-xl font-semibold flex items-center">
                                <i class="fas fa-chart-line mr-3"></i>数据可视化
                            </h2>
                        </div>
                        <div class="p-6">
                            <div id="visualization" class="min-h-200">
                                <div class="text-gray-400 text-center py-12">
                                    <i class="fas fa-chart-bar text-4xl mb-3"></i>
                                    <p class="text-lg">可视化图表将显示在这里</p>
                                    <p class="text-sm mt-2">执行查询后会自动生成图表</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 快速操作卡片 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h3 class="text-lg font-semibold mb-4 flex items-center">
                        <i class="fas fa-bolt mr-2"></i>快速操作
                    </h3>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <button onclick="quickAction('create_table')" class="p-4 bg-blue-50 border border-blue-200 rounded-lg hover:bg-blue-100 transition-colors">
                            <i class="fas fa-plus-circle text-blue-500 text-xl mb-2"></i>
                            <div class="font-medium text-blue-700">新建表</div>
                        </button>
                        <button onclick="quickAction('backup')" class="p-4 bg-green-50 border border-green-200 rounded-lg hover:bg-green-100 transition-colors">
                            <i class="fas fa-shield-alt text-green-500 text-xl mb-2"></i>
                            <div class="font-medium text-green-700">备份数据</div>
                        </button>
                        <button onclick="quickAction('analyze')" class="p-4 bg-purple-50 border border-purple-200 rounded-lg hover:bg-purple-100 transition-colors">
                            <i class="fas fa-chart-pie text-purple-500 text-xl mb-2"></i>
                            <div class="font-medium text-purple-700">性能分析</div>
                        </button>
                        <button onclick="quickAction('export')" class="p-4 bg-orange-50 border border-orange-200 rounded-lg hover:bg-orange-100 transition-colors">
                            <i class="fas fa-file-export text-orange-500 text-xl mb-2"></i>
                            <div class="font-medium text-orange-700">导出数据</div>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 示例模态框 -->
    <div id="exampleModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
        <div class="bg-white rounded-lg w-11/12 max-w-4xl max-h-90vh overflow-hidden">
            <div class="border-b px-6 py-4 flex justify-between items-center">
                <h3 class="text-xl font-semibold">SQL 学习示例</h3>
                <button onclick="closeModal('exampleModal')" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="p-6 overflow-y-auto max-h-96">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4" id="exampleList">
                    <!-- 示例将通过JS动态加载 -->
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentTheme = 'light';
        let sqlHistory = JSON.parse(localStorage.getItem('sqlHistory')) || [];
        let currentData = [];

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('初始化应用...');
            initializeApp();
        });

        async function initializeApp() {
            console.log('开始初始化...');
            await loadDatabaseInfo();
            await loadTables();
            loadQuickExamples();
            initializeSearch();
            console.log('初始化完成');
        }

        // 修复：安全的DOM元素获取
        function getElementSafe(id) {
            const element = document.getElementById(id);
            if (!element) {
                console.warn(`元素 #${id} 未找到`);
            }
            return element;
        }

        // 修复：安全的innerHTML设置
        function setInnerHTMLSafe(elementId, html) {
            const element = getElementSafe(elementId);
            if (element) {
                element.innerHTML = html;
            }
        }
        // 修复：创建可视化图表
        function createVisualization(data) {
            const visualization = getElementSafe('visualization');
            if (!visualization || !data || data.length === 0) {
                return;
            }

            try {
                const headers = Object.keys(data[0]);

                // 分析数据类型
                const numericColumns = headers.filter(header => {
                    return data.some(row => {
                        const value = row[header];
                        return value !== null && !isNaN(parseFloat(value)) && isFinite(value);
                    });
                });

                const textColumns = headers.filter(header => {
                    return data.some(row => {
                        const value = row[header];
                        return value !== null && typeof value === 'string' && value.length > 0;
                    });
                });

                // 根据数据类型选择图表类型
                if (numericColumns.length >= 2) {
                    createScatterChart(visualization, data, numericColumns);
                } else if (numericColumns.length >= 1 && textColumns.length >= 1) {
                    createBarChart(visualization, data, numericColumns[0], textColumns[0]);
                } else if (numericColumns.length >= 1) {
                    createPieChart(visualization, data, numericColumns[0]);
                } else if (textColumns.length >= 1) {
                    createWordCloud(visualization, data, textColumns[0]);
                } else {
                    showDataSummary(visualization, data, headers);
                }
            } catch (error) {
                console.error('创建可视化图表失败:', error);
                visualization.innerHTML = `
                    <div class="text-red-500 text-center py-4">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        图表渲染失败: ${error.message}
                    </div>
                `;
            }
        }

        // 创建散点图
        function createScatterChart(container, data, numericColumns) {
            const ctx = document.createElement('canvas');
            container.innerHTML = '<h3 class="font-semibold mb-4">数据分布散点图</h3>';
            container.appendChild(ctx);

            const xColumn = numericColumns[0];
            const yColumn = numericColumns[1] || numericColumns[0];

            const chartData = {
                datasets: [{
                    label: `${xColumn} vs ${yColumn}`,
                    data: data.map(row => ({
                        x: parseFloat(row[xColumn]) || 0,
                        y: parseFloat(row[yColumn]) || 0
                    })),
                    backgroundColor: 'rgba(59, 130, 246, 0.6)',
                    borderColor: 'rgba(59, 130, 246, 1)',
                    borderWidth: 1
                }]
            };

            new Chart(ctx, {
                type: 'scatter',
                data: chartData,
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: `散点图: ${xColumn} vs ${yColumn}`
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `${xColumn}: ${context.parsed.x}, ${yColumn}: ${context.parsed.y}`;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: xColumn
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: yColumn
                            }
                        }
                    }
                }
            });
        }

        // 创建柱状图
        function createBarChart(container, data, numericColumn, categoryColumn) {
            const ctx = document.createElement('canvas');
            container.innerHTML = '<h3 class="font-semibold mb-4">数据分布柱状图</h3>';
            container.appendChild(ctx);

            // 按类别分组并计算数值总和
            const groups = {};
            data.forEach(row => {
                const category = row[categoryColumn] || '未知';
                const value = parseFloat(row[numericColumn]) || 0;
                groups[category] = (groups[category] || 0) + value;
            });

            const categories = Object.keys(groups).slice(0, 10); // 限制显示数量
            const values = categories.map(cat => groups[cat]);

            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: categories,
                    datasets: [{
                        label: numericColumn,
                        data: values,
                        backgroundColor: [
                            'rgba(59, 130, 246, 0.8)',
                            'rgba(16, 185, 129, 0.8)',
                            'rgba(245, 158, 11, 0.8)',
                            'rgba(239, 68, 68, 0.8)',
                            'rgba(139, 92, 246, 0.8)'
                        ],
                        borderColor: [
                            'rgba(59, 130, 246, 1)',
                            'rgba(16, 185, 129, 1)',
                            'rgba(245, 158, 11, 1)',
                            'rgba(239, 68, 68, 1)',
                            'rgba(139, 92, 246, 1)'
                        ],
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: `${categoryColumn} - ${numericColumn} 分布`
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // 创建饼图
        function createPieChart(container, data, numericColumn) {
            const ctx = document.createElement('canvas');
            container.innerHTML = '<h3 class="font-semibold mb-4">数据分布饼图</h3>';
            container.appendChild(ctx);

            // 计算数值分布
            const values = data.map(row => parseFloat(row[numericColumn]) || 0);
            const total = values.reduce((sum, val) => sum + val, 0);

            // 如果数据点太多，进行分组
            const chartData = values.slice(0, 8); // 限制显示数量
            const labels = chartData.map((_, index) => `数据点 ${index + 1}`);

            if (values.length > 8) {
                const others = values.slice(8).reduce((sum, val) => sum + val, 0);
                chartData.push(others);
                labels.push('其他');
            }

            new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: chartData,
                        backgroundColor: [
                            'rgba(59, 130, 246, 0.8)',
                            'rgba(16, 185, 129, 0.8)',
                            'rgba(245, 158, 11, 0.8)',
                            'rgba(239, 68, 68, 0.8)',
                            'rgba(139, 92, 246, 0.8)',
                            'rgba(236, 72, 153, 0.8)',
                            'rgba(8, 145, 178, 0.8)',
                            'rgba(20, 184, 166, 0.8)',
                            'rgba(120, 113, 108, 0.8)'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        title: {
                            display: true,
                            text: `${numericColumn} 分布`
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const value = context.parsed;
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${context.label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    }
                }
            });
        }

        // 创建文本数据摘要
        function createWordCloud(container, data, textColumn) {
            // 简单的词频统计
            const wordCount = {};
            data.forEach(row => {
                const text = String(row[textColumn] || '');
                const words = text.split(/\s+/).filter(word => word.length > 1);
                words.forEach(word => {
                    wordCount[word] = (wordCount[word] || 0) + 1;
                });
            });

            // 取前20个最常出现的词
            const topWords = Object.entries(wordCount)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 20);

            container.innerHTML = `
                <h3 class="font-semibold mb-4">文本数据词频分析</h3>
                <div class="bg-gray-50 p-4 rounded-lg">
                    <div class="flex flex-wrap gap-2">
                        ${topWords.map(([word, count]) => `
                            <span class="inline-block px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm"
                                  style="font-size: ${Math.max(12, Math.min(24, count * 2))}px">
                                ${word} <span class="text-xs opacity-75">(${count})</span>
                            </span>
                        `).join('')}
                    </div>
                    <div class="mt-3 text-sm text-gray-600">
                        共分析 ${data.length} 条记录，${Object.keys(wordCount).length} 个不同词汇
                    </div>
                </div>
            `;
        }

        // 显示数据摘要
        function showDataSummary(container, data, headers) {
            container.innerHTML = `
                <h3 class="font-semibold mb-4">数据摘要</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="bg-blue-50 p-4 rounded-lg">
                        <div class="text-blue-600 font-semibold">基本统计</div>
                        <div class="text-sm text-gray-600 mt-2">
                            <div>总记录数: ${data.length}</div>
                            <div>字段数量: ${headers.length}</div>
                        </div>
                    </div>
                    <div class="bg-green-50 p-4 rounded-lg">
                        <div class="text-green-600 font-semibold">字段预览</div>
                        <div class="text-sm text-gray-600 mt-2">
                            ${headers.slice(0, 5).map(header => `
                                <div>${header}: ${getColumnSummary(data, header)}</div>
                            `).join('')}
                            ${headers.length > 5 ? `<div>... 还有 ${headers.length - 5} 个字段</div>` : ''}
                        </div>
                    </div>
                </div>
                <div class="mt-4 bg-gray-50 p-4 rounded-lg">
                    <div class="text-gray-600 font-semibold">数据样例</div>
                    <div class="text-xs font-mono bg-white p-2 rounded mt-2 max-h-32 overflow-y-auto">
                        ${JSON.stringify(data.slice(0, 3), null, 2)}
                    </div>
                </div>
            `;
        }

        // 获取列数据摘要
        function getColumnSummary(data, column) {
            const values = data.map(row => row[column]).filter(val => val !== null && val !== undefined);
            if (values.length === 0) return '无数据';

            const sample = values[0];
            if (typeof sample === 'number') {
                const nums = values.map(v => parseFloat(v)).filter(v => !isNaN(v));
                if (nums.length > 0) {
                    const avg = (nums.reduce((a, b) => a + b, 0) / nums.length).toFixed(2);
                    return `数值型, 平均值: ${avg}`;
                }
            }

            if (typeof sample === 'string') {
                const uniqueCount = new Set(values).size;
                return `文本型, ${uniqueCount} 个不同值`;
            }

            return `${typeof sample} 类型`;
        }

        // 修复：加载数据库信息时更新总数据量
        async function loadDatabaseInfo() {
            try {
                console.log('加载数据库信息...');
                const response = await fetch('/api/database/info');

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const result = await response.json();
                console.log('数据库信息响应:', result);

                if (result.success) {
                    // 安全地更新DOM元素
                    const tableCountElement = getElementSafe('tableCount');
                    const totalRowsElement = getElementSafe('totalRows');
                    const dbInfoElement = getElementSafe('dbInfo');

                    if (tableCountElement) {
                        tableCountElement.textContent = result.table_count || '0';
                    }

                    if (totalRowsElement) {
                        totalRowsElement.textContent = result.total_rows ? result.total_rows.toLocaleString() : '0';
                    }

                    if (dbInfoElement) {
                        dbInfoElement.innerHTML = `
                            <div class="space-y-2">
                                <div><span class="font-medium">版本:</span> ${result.version || 'Unknown'}</div>
                                <div><span class="font-medium">当前数据库:</span> ${result.current_database}</div>
                                <div><span class="font-medium">数据库数量:</span> ${result.databases ? result.databases.length : 0}</div>
                                <div><span class="font-medium">总数据量:</span> ${result.total_rows ? result.total_rows.toLocaleString() : 0} 行</div>
                            </div>
                        `;
                    }

                    showNotification('数据库信息加载成功', 'success');
                } else {
                    throw new Error(result.error || '未知错误');
                }
            } catch (error) {
                console.error('加载数据库信息失败:', error);
                showNotification('加载数据库信息失败: ' + error.message, 'error');

                // 设置默认值
                const tableCountElement = getElementSafe('tableCount');
                const totalRowsElement = getElementSafe('totalRows');
                if (tableCountElement) tableCountElement.textContent = '0';
                if (totalRowsElement) totalRowsElement.textContent = '0';
            }
        }



        // 修复：加载表列表
        async function loadTables() {
            try {
                console.log('加载表列表...');
                const response = await fetch('/api/tables');

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const result = await response.json();
                console.log('表列表响应:', result);

                const tableListElement = getElementSafe('tableList');
                if (!tableListElement) return;

                if (result.success) {
                    if (!result.data || result.data.length === 0) {
                        tableListElement.innerHTML = `
                            <div class="text-center py-8 text-gray-500">
                                <i class="fas fa-inbox text-3xl mb-3"></i>
                                <p>暂无数据表</p>
                                <button onclick="createNewTable()" class="mt-3 text-blue-500 hover:text-blue-700 text-sm">
                                    <i class="fas fa-plus mr-1"></i>创建第一个表
                                </button>
                            </div>
                        `;
                        return;
                    }

                    // 渲染表列表
                    tableListElement.innerHTML = result.data.map(table => `
                        <div class="table-item border border-gray-200 rounded-lg p-4 hover:border-blue-300 hover:bg-blue-50 cursor-pointer transition-all duration-200"
                             onclick="showTableDetail('${table.name}')"
                             data-table-name="${table.name ? table.name.toLowerCase() : ''}">
                            <div class="flex justify-between items-start mb-2">
                                <div class="flex items-center">
                                    <i class="fas fa-table text-blue-500 mr-2"></i>
                                    <div class="font-semibold text-gray-800">${table.name || '未知表'}</div>
                                </div>
                                <span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full">${table.row_count || 0} 行</span>
                            </div>
                            <div class="text-xs text-gray-600 space-y-1">
                                ${table.structure && table.structure.slice(0, 2).map(col => `
                                    <div class="flex justify-between">
                                        <span>${col.Field || '未知字段'}</span>
                                        <span class="text-gray-400">${col.Type || ''}</span>
                                    </div>
                                `).join('') || '<div class="text-gray-400">无结构信息</div>'}
                                ${table.structure && table.structure.length > 2 ?
                                    `<div class="text-center text-gray-400">... ${table.structure.length - 2} 更多列</div>` : ''}
                            </div>
                        </div>
                    `).join('');

                } else {
                    throw new Error(result.error || '加载表列表失败');
                }
            } catch (error) {
                console.error('加载表列表失败:', error);
                const tableListElement = getElementSafe('tableList');
                if (tableListElement) {
                    tableListElement.innerHTML = `
                        <div class="text-center py-8 text-red-500">
                            <i class="fas fa-exclamation-triangle text-3xl mb-3"></i>
                            <p>加载表列表失败</p>
                            <p class="text-sm">${error.message}</p>
                            <button onclick="loadTables()" class="mt-3 text-blue-500 hover:text-blue-700 text-sm">
                                <i class="fas fa-sync-alt mr-1"></i>重试
                            </button>
                        </div>
                    `;
                }
            }
        }

        // 修复：执行SQL
        async function executeSQL() {
            const sqlEditor = getElementSafe('sqlEditor');
            if (!sqlEditor) return;

            const sql = sqlEditor.value.trim();
            if (!sql) {
                showNotification('请输入SQL语句', 'warning');
                return;
            }

            // 保存到历史记录
            saveToHistory(sql);

            const resultDiv = getElementSafe('sqlResult');
            if (resultDiv) {
                resultDiv.innerHTML = `
                    <div class="flex items-center justify-center py-8">
                        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mr-3"></div>
                        <span>正在执行SQL语句...</span>
                    </div>
                `;
            }

            try {
                const response = await fetch('/api/sql/execute', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ sql: sql })
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误: ${response.status}`);
                }

                const result = await response.json();
                console.log('SQL执行结果:', result);

                if (result.success) {
                    if (result.type === 'query' && result.data && result.data.length > 0) {
                        displayQueryResult(result.data, result.rowcount);
                        createVisualization(result.data);
                    } else {
                        displayUpdateResult(result);
                    }
                } else {
                    displayErrorResult(result.error);
                }

                // 刷新表列表
                await loadTables();

            } catch (error) {
                console.error('执行SQL失败:', error);
                displayErrorResult('网络请求失败: ' + error.message);
            }
        }

        // 修复：显示查询结果
        function displayQueryResult(data, rowCount) {
            const resultDiv = getElementSafe('sqlResult');
            if (!resultDiv || !data || data.length === 0) return;

            const headers = Object.keys(data[0]);
            currentData = data; // 保存数据用于导出

            resultDiv.innerHTML = `
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <span class="bg-green-100 text-green-800 text-sm px-3 py-1 rounded-full">
                            <i class="fas fa-check-circle mr-1"></i>查询成功
                        </span>
                        <span class="text-sm text-gray-600 ml-2">返回 ${rowCount} 行数据</span>
                    </div>
                    <button onclick="exportToCSV()" class="text-blue-500 hover:text-blue-700 text-sm">
                        <i class="fas fa-download mr-1"></i>导出CSV
                    </button>
                </div>
                <div class="result-table border border-gray-200 rounded-lg overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full bg-white">
                            <thead class="bg-gray-50">
                                <tr>
                                    ${headers.map(header => `
                                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider border-b">
                                            ${header}
                                        </th>
                                    `).join('')}
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                                ${data.map((row, index) => `
                                    <tr class="${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'} hover:bg-blue-50">
                                        ${headers.map(header => `
                                            <td class="px-4 py-3 text-sm text-gray-900 border-b whitespace-nowrap">
                                                ${formatCellValue(row[header])}
                                            </td>
                                        `).join('')}
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
        }

        // 修复：显示错误结果
        function displayErrorResult(error) {
            const resultDiv = getElementSafe('sqlResult');
            if (resultDiv) {
                resultDiv.innerHTML = `
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
                        <div class="flex">
                            <i class="fas fa-exclamation-circle mr-2 mt-1"></i>
                            <div>
                                <strong>执行失败!</strong>
                                <div class="text-sm mt-1">${error}</div>
                            </div>
                        </div>
                    </div>
                `;
            }
        }

        // 修复：显示更新结果
        function displayUpdateResult(result) {
            const resultDiv = getElementSafe('sqlResult');
            if (resultDiv) {
                resultDiv.innerHTML = `
                    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded">
                        <div class="flex">
                            <i class="fas fa-check-circle mr-2 mt-1"></i>
                            <div>
                                <strong>执行成功!</strong>
                                <div class="text-sm">影响行数: ${result.data && result.data.affected_rows ? result.data.affected_rows : result.rowcount || 0}</div>
                            </div>
                        </div>
                    </div>
                `;
            }
        }

        // 其他函数保持不变...
        function formatCellValue(value) {
            if (value === null || value === undefined) return '<span class="text-gray-400">NULL</span>';
            if (typeof value === 'boolean') return value ? 'TRUE' : 'FALSE';
            if (typeof value === 'object') return JSON.stringify(value);
            return String(value);
        }

        function showNotification(message, type = 'info') {
            const colors = {
                info: 'blue',
                success: 'green',
                warning: 'yellow',
                error: 'red'
            };

            const color = colors[type];
            const notification = document.createElement('div');
            notification.className = `fixed top-4 right-4 bg-${color}-100 border border-${color}-400 text-${color}-700 px-6 py-3 rounded-lg shadow-lg z-50`;
            notification.innerHTML = `
                <div class="flex items-center">
                    <i class="fas fa-${type === 'success' ? 'check' : 'exclamation-triangle'} mr-2"></i>
                    <span>${message}</span>
                </div>
            `;

            document.body.appendChild(notification);
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 5000);
        }

        function clearEditor() {
            const sqlEditor = getElementSafe('sqlEditor');
            if (sqlEditor) {
                sqlEditor.value = '';
            }
        }

        function refreshTables() {
            loadTables();
            loadDatabaseInfo();
            showNotification('表列表已刷新', 'success');
        }

        function createNewTable() {
            const sql = `CREATE TABLE example_table (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`;
            const sqlEditor = getElementSafe('sqlEditor');
            if (sqlEditor) {
                sqlEditor.value = sql;
            }
            showNotification('已生成建表模板，请修改后执行', 'info');
        }

        // 初始化搜索功能
        function initializeSearch() {
            const searchInput = getElementSafe('tableSearch');
            if (searchInput) {
                searchInput.addEventListener('input', function(e) {
                    const searchTerm = e.target.value.toLowerCase();
                    const tableItems = document.querySelectorAll('.table-item');

                    tableItems.forEach(item => {
                        const tableName = item.getAttribute('data-table-name') || '';
                        if (tableName.includes(searchTerm)) {
                            item.style.display = 'block';
                        } else {
                            item.style.display = 'none';
                        }
                    });
                });
            }
        }

        // 其他辅助函数...
        function exportToCSV() {
            if (!currentData || currentData.length === 0) {
                showNotification('没有数据可导出', 'warning');
                return;
            }

            const headers = Object.keys(currentData[0]);
            const csvContent = [
                headers.join(','),
                ...currentData.map(row => headers.map(header => {
                    const value = row[header];
                    return typeof value === 'string' && value.includes(',') ? `"${value}"` : value;
                }).join(','))
            ].join('\n');

            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', 'export.csv');
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            showNotification('数据已导出为CSV文件', 'success');
        }

        function formatSQL() {
            const sqlEditor = getElementSafe('sqlEditor');
            if (!sqlEditor) return;

            let sql = sqlEditor.value;
            sql = sql
                .replace(/\b(SELECT|FROM|WHERE|INSERT INTO|UPDATE|DELETE FROM|CREATE TABLE|ALTER TABLE|DROP TABLE|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|OUTER JOIN|ON|GROUP BY|ORDER BY|HAVING|LIMIT|VALUES|SET)\b/gi, '\n$1')
                .replace(/,/g, ',\n    ')
                .replace(/\)/g, '\n)');

            sqlEditor.value = sql;
            showNotification('SQL已格式化', 'info');
        }

        function saveSQL() {
            const sqlEditor = getElementSafe('sqlEditor');
            if (!sqlEditor) return;

            const sql = sqlEditor.value;
            if (!sql.trim()) {
                showNotification('没有SQL语句可保存', 'warning');
                return;
            }

            localStorage.setItem('saved_sql', sql);
            showNotification('SQL语句已保存到本地', 'success');
        }

        function saveToHistory(sql) {
            const timestamp = new Date().toLocaleString();
            sqlHistory.unshift({ sql, timestamp });
            sqlHistory = sqlHistory.slice(0, 50);
            localStorage.setItem('sqlHistory', JSON.stringify(sqlHistory));
        }

        function showTableDetail(tableName) {
            const sqlEditor = getElementSafe('sqlEditor');
            if (sqlEditor) {
                sqlEditor.value = `SELECT * FROM \`${tableName}\` LIMIT 20;`;
            }
            executeSQL();
        }

        function showExamples() {
            const modal = getElementSafe('exampleModal');
            if (modal) {
                modal.classList.remove('hidden');
            }
        }

        function closeModal(modalId) {
            const modal = getElementSafe(modalId);
            if (modal) {
                modal.classList.add('hidden');
            }
        }

        function loadQuickExamples() {
            const examples = [
                {
                    title: '创建用户表',
                    sql: `CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`,
                    description: '学习创建基本表结构'
                },
                {
                    title: '插入数据',
                    sql: `INSERT INTO users (username, email) VALUES
('john_doe', 'john@example.com'),
('jane_smith', 'jane@example.com');`,
                    description: '学习插入数据'
                },
                {
                    title: '查询数据',
                    sql: `SELECT * FROM users WHERE username LIKE 'j%';`,
                    description: '学习基础查询'
                },
                {
                    title: '更新数据',
                    sql: `UPDATE users SET email = 'new_email@example.com' WHERE username = 'john_doe';`,
                    description: '学习更新数据'
                }
            ];

            const exampleList = getElementSafe('exampleList');
            if (exampleList) {
                exampleList.innerHTML = examples.map(example => `
                    <div class="border border-gray-200 rounded-lg p-4 hover:border-blue-300 cursor-pointer"
                         onclick="loadExample('${example.sql.replace(/'/g, "\\'")}')">
                        <div class="font-semibold text-blue-600">${example.title}</div>
                        <div class="text-sm text-gray-600 mt-1">${example.description}</div>
                        <div class="text-xs text-gray-400 mt-2 font-mono truncate">${example.sql}</div>
                    </div>
                `).join('');
            }
        }

        function loadExample(sql) {
            const sqlEditor = getElementSafe('sqlEditor');
            if (sqlEditor) {
                sqlEditor.value = sql;
            }
            closeModal('exampleModal');
        }

        function quickAction(action) {
            const actions = {
                create_table: `CREATE TABLE example_table (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(150) UNIQUE,
    age INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`,
                backup: `-- 创建备份表
CREATE TABLE users_backup AS SELECT * FROM users;`,
                analyze: `-- 分析表性能
SHOW TABLE STATUS LIKE 'users';`,
                export: `-- 导出数据示例
SELECT * FROM users;`
            };

            if (actions[action]) {
                const sqlEditor = getElementSafe('sqlEditor');
                if (sqlEditor) {
                    sqlEditor.value = actions[action];
                }
                showNotification(`已加载${action}示例`, 'info');
            }
        }

        function toggleTheme() {
            currentTheme = currentTheme === 'light' ? 'dark' : 'light';
            document.body.classList.toggle('bg-gray-900');
            document.body.classList.toggle('text-white');
            showNotification(`已切换到${currentTheme === 'light' ? '浅色' : '深色'}主题`, 'info');
        }

        function exportData() {
            showNotification('导出功能开发中...', 'info');
        }

        function showHistory() {
            showNotification('历史记录功能开发中...', 'info');
        }

        function createVisualization(data) {
            // 可视化功能占位
            const visualization = getElementSafe('visualization');
            if (visualization) {
                visualization.innerHTML = `
                    <div class="text-gray-400 text-center py-8">
                        <i class="fas fa-chart-bar text-3xl mb-3"></i>
                        <p>可视化功能开发中</p>
                    </div>
                `;
            }
        }
    </script>
</body>
</html>